import datetime
import sys
import json

import click
import flask
import waitress



from .config import Config, InvalidTokenException
from .handler import EventHander, UnsupportedRepoError
from .payload import Payload

def create_app(config):
    app = flask.Flask(__name__)
    
    @app.route('/webhook', methods=['POST'])
    def webhook():
        data = flask.request.get_data()
        try:
            event = str(flask.request.headers['X-AtomGit-Event'])
            delivery = str(flask.request.headers['X-AtomGit-Delivery'])
            # signature = str(flask.request.headers['X-Hub-Signature'])
        except KeyError:
            return 'Webhook headers required are missing\n', 400

        try:
            payload = json.loads(data)
        except (KeyError, ValueError):
            return 'Error: missing or invalid payload\n', 400
        try:
            handler = EventHander(Payload(payload))
            return handler.run(event, config)
        except UnsupportedRepoError:
            return 'Error: this repository is not configured!\n', 400
        except:
            print()
            print('An exception occured while processing a webhook!')
            print('Time:', datetime.datetime.now())
            print('Delivery ID:', delivery)
            print('Event name:', event)
            print('Paybook', payload)
            return 'Internal server error\n', 500

    @app.route('/')
    def index():
        return '大香蕉,一条大香蕉,你的感觉真的很奇妙~！\n'

    return app

@click.command()
@click.option('--port', default=8000)
def try_main(port):
    try:
        config = Config()
    except InvalidTokenException:
        print('error: invalid Atomgit token provided!')
        sys.exit(1)
    print('服务启动！！！')
    app = create_app(config)
    waitress.serve(app, port=port)

def main():
    try_main()